<template>
    <div class="add_shop_container">
        <div class="form_card">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
                <el-form-item label="店铺名称" prop="shopName">
                    <el-input
                        v-model.trim="form.shopName"
                        show-word-limit
                        maxlength="20"
                        placeholder="请输入店铺名称，不超过20个字" />
                </el-form-item>
                <el-form-item label="店铺类型" prop="type">
                    <el-select v-model="form.type" placeholder="请选择店铺类型">
                        <el-option
                            v-for="(item, index) in shopStatus"
                            :key="index"
                            :value="item.value"
                            :label="item.label">
                        </el-option>
                    </el-select>
                </el-form-item>
                <MapTen ref="MapTenRef" :data="form" @change="onMapChange" />

                <el-form-item label="联系人" prop="contactPerson">
                    <el-input
                        v-model.trim="form.contactPerson"
                        placeholder="请输入联系人姓名"
                        show-word-limit
                        maxlength="10" />
                </el-form-item>
                <el-form-item label="联系电话" prop="tel">
                    <el-input v-model.trim="form.tel" placeholder="请输入联系电话" />
                </el-form-item>
            </el-form>
        </div>
        <div class="btn_card">
            <el-button @click="routerBack">取消</el-button>
            <el-button type="primary" @click="onSubmit(formRef)">保存</el-button>
        </div>
    </div>
</template>

<script setup>
import storage from '@/commons/storage';
import MapTen from '@/components/MapTen.vue';
import { packSelectObjUtil, isMobile } from '@/commons/utils';
import constants from '@/commons/constants';
import request from '@/request';
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue';
import { setLayout, resetLayout } from '@/hooks/layout';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';

const router = useRouter();
const route = useRoute();
const queryShopId = route.query.id;
const shopStatus = reactive(packSelectObjUtil(constants.SHOP_STATUS));
const formRef = ref(null);
const form = reactive({
    shopName: '', // 店铺名称
    contactPerson: '', // 联系人
    tel: '', // 联系电话
    type: '', // 店铺类型 1：加盟   2：直营
    areaText: [], // 原退货地址改为店铺地址
    provinceId: '', // 省份id
    cityId: '', // 城市id
    areaId: '', // 地区id
    townId: '', // 乡镇id
    address: '', //  详细地址
    street: '', //  详细地址
    lat: '', //  纬度 6位小数
    lng: '' // 经度
});

const validatePhone = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入手机号'));
    } else if (isMobile(value)) {
        callback();
    } else {
        callback(new Error('请输入正确的手机号!'));
    }
};
const rules = reactive({
    contactPerson: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
    shopName: [{ required: true, message: '店铺名称不能为空', trigger: 'blur' }],
    type: [{ required: true, message: '店铺类型不能为空' }],
    status: [{ required: true, message: '店铺状态不能为空' }],
    tel: [
        { required: true, message: '手机号不能为空', trigger: 'blur' },
        { validator: validatePhone, trigger: 'blur' }
    ]
});

const routerBack = () => {
    router.back();
};

const MapTenRef = ref(null);
const onMapChange = v => {
    Object.assign(form, v);
    nextTick(() => {
        form.street && formRef.value.validateField('street');
        form.area?.length && formRef.value.validateField('area');
        form.lng && formRef.value.validateField('lng');
    });
};

/* 获取店铺详情 */
const getDetail = async () => {
    const { data } = await request('shopDetail', { shopId: queryShopId });
    for (const [key, value] of Object.entries(form)) {
        form[key] = data[key];
    }
    form.area = [form.provinceId, data.cityId, data.areaId, data.townId].filter(Boolean);
    MapTenRef.value.onShowMap(data);
};

/* 新增 */
const onAdd = async () => {
    await request('addShop', form);
    ElMessage.success('新增成功');
    routerBack();
};

/* 编辑 */
const onEdit = async () => {
    await request('editShop', form);
    ElMessage.success('编辑成功');
    routerBack();
};

/* 保存 */
const onSubmit = async formEl => {
    if (!formEl) return;
    await formEl.validate(async valid => {
        if (valid) {
            queryShopId ? onEdit() : onAdd();
        }
    });
};

onMounted(() => {
    storage.set('SEARCH_RESET', false);
    if (queryShopId) {
        form.shopId = queryShopId;
        getDetail();
    } else {
        MapTenRef.value.onShowMap();
    }
    setLayout();
});
onUnmounted(() => {
    resetLayout();
});
</script>

<style lang="scss" src="./index.scss" scoped></style>
